import "ol/ol.css";
import Map from "ol/Map";
import OSM from "ol/source/OSM";
import TileLayer from "ol/layer/Tile";
import ImageLayer from 'ol/layer/Image';
import {Raster as RasterSource} from 'ol/source';
import XYZ from "ol/source/XYZ";
import {get,Projection,addProjection,addCoordinateTransforms} from 'ol/proj'
import {getWidth,getTopLeft} from 'ol/extent'
import TileGrid from 'ol/tilegrid/TileGrid'
// 自己的tk
// let TK = '2b7cbf61123cbe4e9ec6267a87e7442f';
let TK = '4697d231b5655bf4aa67a04221da58d9';


let getUrl = function (type) {
    let url = 'http://t{randomNumber}.tianditu.gov.cn/DataServer?T={type}&x={x}&y={y}&l={z}';
    url = url.replace('{randomNumber}', Math.round(Math.random() * 7).toString());
    url = url.replace('{type}', type);
    url = url + "&tk=" + TK;
    return url;
}

let getResolutionsExpert = function (size) {

    let resolutions = new Array(18);
    let matrixIds = new Array(18);
    for (let z = 0; z < 19; ++z) {
        //分辨率
        resolutions[z] = size / Math.pow(2, z);
        //放大等级
        matrixIds[z] = z;
    }
    return resolutions;
}

let getOptional = function (url) {

    let projection = get('EPSG:4326');
    let projectionExtent = projection.getExtent();
    let size = getWidth(projectionExtent) / 256;

    return new XYZ({
        crossOrigin: 'anonymous',
        wrapX: true,
        //切片xyz获取方法
        tileUrlFunction: function (tileCoord) {
            const z = tileCoord[0];
            const x = tileCoord[1];
            let y = tileCoord[2];
            let completeUrl = url.replace('{z}', z.toString())
                .replace('{y}', y.toString())
                .replace('{x}', x.toString());
            return completeUrl;
        },
        //坐标系
        projection: projection,
        tileGrid: new TileGrid({
            origin: getTopLeft(projectionExtent),
            tileSize: [256, 256],
            //分辨率数组 天地图为 1.40625
            // resolutions: getResolutions(1.40625, 22)
            resolutions: getResolutionsExpert(size)
        }),
    })
}

// const type = 'w'; // 墨卡托
let TYPE = 'c';  // WGS84
//影像图
let IMG_C = 'img_' + TYPE;
let CIA_C = 'cia_' + TYPE;
let IBO_C = 'ibo_' + TYPE;

let VEC_C = 'vec_' + TYPE;
let CVA_C = 'cva_' + TYPE;
//影像图
function getIMG_CLayer() {
    let layer = new ol.layer.Tile({
        name: "天地图影像图层",
        source: getOptional(getUrl(IMG_C))
    });
    return layer;
}

export function getVEC_CLayer() {
    let layer = new TileLayer({
        title:'天地图',
        name: "天地图",
        source: getOptional(getUrl(VEC_C))
    });
    let layerColor = new ImageLayer({
        title:'天地图',
        name: "天地图",
        source: getSource(layer, 'black')
    });
    return layerColor;
}

export function getCVA_CLayer() {
    let layer = new TileLayer({
        title: "天地图标注",
        name: "天地图标注",
        source: getOptional(getUrl(CVA_C)),

    });
    let layerColor = new ImageLayer({
        title: "天地图标注",
        name: "天地图标注",
        source: getSource(layer, 'gray'),
        visible:false
    });
    return layerColor;
}

function getCIA_CLayer() {
    console.log('123')
    let layer = new ol.layer.Tile({
        name: "天地图影像注记图层",
        source: getOptional(getUrl(CIA_C)),
        zIndex: 1,
    });
    return layer;
}

function getIBO_CLayer() {
    let layer = new ol.layer.Tile({
        name: "天地图影像境界图层",
        source: getOptional(getUrl(IBO_C)),
        zIndex: 1,
    });
    return layer;
}

/**
 * Created by Eric on 2018/3/12.
 * updated by S-jor on 2018/12/01
 */

function getSource(layer, type) {

    let reverseFunc = undefined
    if (type == 'gray') {
        reverseFunc = function (pixelsTemp) {
            //灰色
            for (var i = 0; i < pixelsTemp.length; i += 4) {
                var r = pixelsTemp[i];
                var g = pixelsTemp[i + 1];
                var b = pixelsTemp[i + 2];
                //运用图像学公式，设置灰度值
                var grey = r * 0.3 + g * 0.59 + b * 0.11;
                //将rgb的值替换为灰度值
                pixelsTemp[i] = grey;
                pixelsTemp[i + 1] = grey;
                pixelsTemp[i + 2] = grey;
            }
        };
    } else if (type == 'blue') {
        reverseFunc = function (pixelsTemp) {
            //蓝色
            for (var i = 0; i < pixelsTemp.length; i += 4) {
                var r = pixelsTemp[i];
                var g = pixelsTemp[i + 1];
                var b = pixelsTemp[i + 2];
                //运用图像学公式，设置灰度值
                var grey = r * 0.3 + g * 0.59 + b * 0.11;
                //将rgb的值替换为灰度值
                pixelsTemp[i] = grey;
                pixelsTemp[i + 1] = grey;
                pixelsTemp[i + 2] = grey;

                pixelsTemp[i] = 55 - pixelsTemp[i];
                pixelsTemp[i + 1] = 255 - pixelsTemp[i + 1];
                pixelsTemp[i + 2] = 305 - pixelsTemp[i + 2];
            }
        };
    } else if (type == 'black') {
        reverseFunc = function (pixelsTemp) {
            //灰色
            for (var i = 0; i < pixelsTemp.length; i += 4) {
                var r = pixelsTemp[i];
                var g = pixelsTemp[i + 1];
                var b = pixelsTemp[i + 2];
                //运用图像学公式，设置灰度值
                var grey = r * 0.3 + g * 0.59 + b * 0.11;
                //将rgb的值替换为灰度值
                pixelsTemp[i] = grey;
                pixelsTemp[i + 1] = grey;
                pixelsTemp[i + 2] = grey;

                //黑色，依赖上边的灰色
                pixelsTemp[i] = 255 - pixelsTemp[i];
                pixelsTemp[i + 1] = 255 - pixelsTemp[i + 1];
                pixelsTemp[i + 2] = 255 - pixelsTemp[i + 2];
            }
        };
    } else if (type == 'reversal') {
        reverseFunc = function (pixelsTemp) {
            //反转色
            for (var i = 0; i < pixelsTemp.length; i += 4) {
                pixelsTemp[i] = 255 - pixelsTemp[i];
                pixelsTemp[i + 1] = 255 - pixelsTemp[i + 1];
                pixelsTemp[i + 2] = 255 - pixelsTemp[i + 2];
            }
        };
    }

    if (reverseFunc) {
        const raster = new RasterSource({
            sources: [
                layer,
            ],
            operationType: 'image',
            operation: function (pixels, data) {
                reverseFunc(pixels[0].data)
                return pixels[0];
            },
            threads: 10,
            lib: {
                reverseFunc: reverseFunc,
            }

        });
        // raster.refresh()
        return raster;
    } else {
        return layer;
    }
}

export default getVEC_CLayer()
